<template>
  <div class="auth-container">
    <el-header class="auth-header">
      <Back style="margin-top: 25px; color: white;" @click="back" />
      <h1 v-if="!title" style="color: red">请先选择一个比赛</h1>
      <h1>{{ title }}</h1>
    </el-header>
    <el-container>
      <div class="main">
        <el-main v-show="isLogin" class="auth-main">
          <el-tabs v-model="activeTab" stretch>
            <el-tab-pane label="用户登录" name="login">
              <el-form :model="loginForm" label-width="80px" class="auth-form">
                <el-form-item label="用户名">
                  <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                  <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item class="auth-links">
                  <el-checkbox v-model="loginForm.saveCredentials">保存用户名和密码</el-checkbox>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" class="auth-button" @click="login">登录</el-button>
                </el-form-item>
                <span style="font-size: 10px; margin-left: 92%;" @click="togetwang">忘记密码</span>
                <el-form-item class="auth-links">
                  <a :href="`${url}${enableDocument}`">服务条款</a>
                </el-form-item>
                <el-form-item class="auth-links">
                  <a href="#">隐私政策</a>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="用户注册" name="register">
              <!-- 注册表单 -->
              <el-form :model="registerForm" label-width="100px" class="auth-form">
                <el-form-item label="用户名">
                  <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                  <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="确认手机号">
                  <el-input v-model="registerForm.aginphone" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                  <el-input type="password" v-model="registerForm.password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码">
                  <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请确认密码"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" class="auth-button" @click="register">注册</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="管理员登录" name="adminLogin">
              <!-- 管理员登录表单 -->
              <el-form :model="adminLoginForm" label-width="80px" class="auth-form">
                <el-form-item label="用户名">
                  <el-input v-model="adminLoginForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                  <el-input type="password" v-model="adminLoginForm.password" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item class="auth-links">
                  <el-checkbox v-model="adminLoginForm.saveCredentials">保存用户名和密码</el-checkbox>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" class="auth-button" @click="adminLogin">登录</el-button>
                </el-form-item>
                <span style="font-size: 10px; margin-left: 92%;" @click="togetwang">忘记密码</span>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </div>
    </el-container>
  </div>
  <div class="auth-container">
    <div class="main">
      <div v-show="!isLogin" class="auth-main">
        <el-tabs v-model="getwang" stretch>
          <el-tab-pane label="修改密码" name="getwang">
            <!-- 注册表单 -->
            <el-form :model="reviseForm" label-width="80px" class="auth-form">
              <span class="tishi">输入完整用户名和手机号更改密码</span>
              <el-form-item label="用户名">
                <el-input v-model="reviseForm.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item label="手机号">
                <el-input v-model="reviseForm.phone" placeholder="请输入手机号"></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input type="password" v-model="reviseForm.password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item label="确认密码">
                <el-input type="password" v-model="reviseForm.revisePassword" placeholder="请确认密码"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="success" @click="quxiaorevise">取消修改</el-button>
                <el-button type="primary" @click="revise">修改密码</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';
import { useMatchIdStore } from '../store/matchid.js';
import { useTeamStore } from '../store/teamgroupid.js';
import { ElMessage } from 'element-plus';
// 引入处理登录和注册的API函数

const matchIdStore = useMatchIdStore();
const teamStore = useTeamStore();

const router = useRouter();

const route = useRoute();
const isLogin = ref(true);

const url = ref('http://back1.idcfengye.com:15173');
const enableDocument = ref('');

const id = route.query.competitionId;
const title = route.query.title;
matchIdStore.setMatchName(id)

const loginForm = ref({
  matchId: matchIdStore.matchId,
  username: '',
  password: '',
  role: 'user',
  saveCredentials: false
});

const registerForm = ref({
  username: '',
  phone: '',
  aginphone: '',
  password: '',
  confirmPassword: '',
  role: 'user'
});

const adminLoginForm = ref({
  matchId: matchIdStore.matchId,
  username: '',
  password: '',
  role: 'admin',
  saveCredentials: false
});

const reviseForm = ref({
  username: '',
  phone: '',
  password: '',
  revisePassword: ''
})
const getwang = ref('getwang'); // 默认激活第一个标签页

const activeTab = ref('login'); // 默认激活第一个标签页

//用户登录
const login = async () => {
  if (!title) {
    ElMessage.error('你还未选择比赛');
    router.push({ path: '/' });
    return;
  }
  if (loginForm.saveCredentials.value) {
    // 存储用户名和密码到LocalStorage
    localStorage.setItem('username', loginForm.value.username);
    localStorage.setItem('password', loginForm.value.password);
  } else {
    // 如果不保存凭据，则从LocalStorage中移除
    localStorage.removeItem('username');
    localStorage.removeItem('password');
  }
  if (loginForm.value.username === '' || loginForm.value.password === '') {
    ElMessage.error('用户名或密码不能为空！');
    return;
  }


  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/user/login', loginForm.value);
    if (response.data.success) {
      ElMessage.success('登录成功');
      // 处理登录成功后的逻辑，例如保存token和用户数据
      localStorage.setItem('userToken', response.data.token);
      localStorage.setItem('userData', JSON.stringify(response.data.data));
      // 跳转到主页或其他页面
      teamStore.fetchtoken(response.data.token);
      teamStore.fetchteamgroupid();
      router.push({ path: '/home/homechild', query: { id: matchIdStore.matchId } });
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    ElMessage.error(`用户名或密码错误`);
  }
};

// 注册
const register = async () => {
  if (registerForm.value.password !== '' && registerForm.value.username !== '') {
    if (registerForm.value.password !== registerForm.value.confirmPassword) {
      ElMessage.error('两次输入的密码不一致，请重新输入！');
      return;
    }
  } else {
    ElMessage.error('用户名密码不能为空！');
    return;
  }
  if (!registerForm.value.phone || !/^1\d{10}$/.test(registerForm.value.phone)) {
    ElMessage.error('手机号码格式不正确');
    return;
  }
  if (registerForm.value.aginphone !== registerForm.value.phone) {
    ElMessage.error('两次手机号不同');
    return;
  }
  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/user/reguser', registerForm.value);
    if (response.data.success) {
      ElMessage.success('注册成功');
      registerForm.value = {
        username: '',
        phone: '',
        aginphone: '',
        password: '',
        confirmPassword: '',
        role: 'user'
      }
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    ElMessage.error(`用户名已被注册`);
  }
};

// 管理员demo登录
const adminLogin = async () => {
  try {
    const response = await
      axios.post('http://back1.idcfengye.com:15173/competition/user/adminLogin', adminLoginForm.value);
    if (response.data.success) {
      ElMessage.success('登录成功');
      // 处理登录成功后的逻辑，例如保存token和用户数据
      const token = response.data.token; // 获取 token
      const adminData = response.data.data; // 获取用户数据
      localStorage.setItem('adminToken', token);
      localStorage.setItem('adminData', JSON.stringify(adminData));
      // 跳转到管理页面
      router.push({ path: '/admin/adminchild' });
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    if (error.response.status === 401) {
      ElMessage.error(`用户名或密码错误`);
    } else {
      if (error.response.status === 403) {
        ElMessage.error(`你没有登录权限`);
      } else {
        ElMessage.error(`登录失败: ${error.message || '未知错误'}`);
      }
    }
  }
};

//忘记密码
function togetwang() {
  isLogin.value = false;
}

//返回登录
function quxiaorevise() {
  isLogin.value = true;
}

//修改密码
async function revise() {
  if (reviseForm.value.password === '' || reviseForm.value.revisePassword === '') {
    ElMessage.error('密码不能为空！');
    return;
  }
  if (reviseForm.value.password !== reviseForm.value.revisePassword) {
    ElMessage.error('两次输入的密码不一致，请重新输入！');
    return;
  }
  if (!reviseForm.value.phone || !/^1\d{10}$/.test(reviseForm.value.phone)) {
    ElMessage.error('手机号码格式不正确');
    return;
  }
  if (reviseForm.value.username === '') {
    ElMessage.error('用户名不能为空！');
    return;
  }
  try {
    const response = await axios.post('http://back1.idcfengye.com:15173/competition/user/update/password', reviseForm.value);
    if (response.data.success) {
      ElMessage.success('修改成功');
    }
  } catch (error) {
    if (error.response.status === 404) {
      ElMessage.error('用户名或手机号不匹配');
    }
  }
}

//获取启用的文件给用户下载
async function document() {
  try {
    const response = await axios.get('http://back1.idcfengye.com:15173/competition/enable/document/true')
    console.log(response);
    enableDocument.value = response.data.document.filepath
  } catch (error) {
    console.log(error);
  }
}

onMounted(() => {
  document();
})

// 在组件创建时检查LocalStorage中的凭据
loginForm.value.username = localStorage.getItem('username') || '';
loginForm.value.password = localStorage.getItem('password') || '';
loginForm.saveCredentials = (loginForm.value.username && loginForm.value.password) ? true : false;

//返回上一级
function back() {
  router.push('/');
}
</script>

<style scoped>
.tishi {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  font-size: 12px;
  /* 设置字体大小 */
  color: red;
  opacity: 0.8;
}

.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100%;
  /* 使用min-height确保至少占满整个视口高度 */
  width: 100%;
}

.el-container {
  margin-top: 8%;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 800px;
  /* 增加宽度为800px */
}

.auth-header {
  height: 100px;
  width: 100%;
  background-color: #2c8fd5;
  color: white;
  text-align: center;
  line-height: 35px;
  font-size: 24px;
}

.auth-main {
  display: flex;
  justify-content: center;
  /* 水平方向上居中 */
  align-items: center;
  /* 垂直方向上居中 */
  min-height: 300px;
  width: 600px;
  /* 设置最小高度 */

  /* 增加浅蓝色背景 */
  /* margin: 5% auto 0 25%; */
}

.main {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #E0F7FF;
  width: 600px;
}

.auth-form {
  width: 500px;
  /* 使表单占满容器宽度 */
}

.auth-form .el-form-item {
  margin-left: 20%;
  width: 55%;
  /* 设置表单项宽度 */
  margin-bottom: 10px;
  /* 设置表单项间距 */
}

.auth-button {
  width: 80%;
  /* 设置按钮宽度 */
}

.auth-links {
  height: 20px;
  font-size: 12px;
  width: 55%;
  /* 设置表单项宽度 */
  margin-bottom: 10px;
}

svg {
  width: 50px;
  height: 50px;
  float: left;
  margin-top: 14px;
}
</style>